﻿/*--------------------------------------------------------------
 * Author : Shine K Velayudhan 
 ---------------------------------------------------------------*/
using System;
using System.IO;

namespace IQN.Cache
{
    /// <summary>
    /// BucketEntry class. Object hold caching details and serialize and deserialize the caching objects.
    /// </summary>
    internal sealed class BucketEntry
    {
        public DateTime AbsoluteExpiration{get;set;}
        public DateTime CreatedOn{get;set;}
        public DateTime LastAccessedOn { get; set; }
        public string DataFileName{get;private set;}
        public string Key { get; private set; }
        public string Id { get; private set; }

        public BucketEntry() { }
        public BucketEntry(string key, DateTime absoluteExpiration, string id)
            : this(key, absoluteExpiration)
        {
            Id = id;
        }

        public BucketEntry(string key, DateTime absoluteExpiration)
        {
            Key = key;
            AbsoluteExpiration = absoluteExpiration;
            DataFileName = Guid.NewGuid().ToString("N").ToUpper() + ".dat";
            CreatedOn = DateTime.UtcNow;
            LastAccessedOn = DateTime.UtcNow;
        }

        public static BucketEntry Deserialize(BinaryReader binIn)
        {
            BucketEntry entry = new BucketEntry();
            entry.Key = binIn.ReadString();
            entry.AbsoluteExpiration = new DateTime(binIn.ReadInt64());
            entry.DataFileName = binIn.ReadString();
            entry.CreatedOn = new DateTime(binIn.ReadInt64());
            entry.LastAccessedOn = new DateTime(binIn.ReadInt64());
            entry.Id = binIn.ReadString();
            return entry;
        }

        public void Serialize(BinaryWriter binOut)
        {
            binOut.Write(Key);
            binOut.Write(AbsoluteExpiration.Ticks);
            binOut.Write(DataFileName);
            binOut.Write(CreatedOn.Ticks);
            binOut.Write(LastAccessedOn.Ticks);
            binOut.Write(Id);
        }
    }
}
